<?php
/**
 * @uses $pgdb
 */
function add_societe()
{
    global $pgdb;
    $error = 0;
    $nom = pg_escape_string($_POST['nom']);
    $siret = pg_escape_string($_POST['siret']);
    $adress = pg_escape_string($_POST['adress']);
    if ($sV = validateSiret($siret)) {
        $error = 1;
        $msg = $sV;
    }
    if ($error == 0) {

        $query = sprintf("INSERT INTO societe(nom, siret, adress) VALUES('%s', '%s', '%s')",
                    $nom,
                    $siret,
                    $adress
                );
        if (pg_query($pgdb, $query)) {
            echo 'Success for add new company';
        } else {
            echo 'Fail to add new societe';
        }
    } else {
        header('Location: add-societe.php?msg='.$msg);
    }
}

function edit_societe()
{
}
function delete_societe($id)
{
    global $pgdb;
    if (pg_query($pgdb, "DELETE FROM societe WHERE id_societe=". $id)) {
        return true;
    } else {
        return false;
    }
}
function get_societe($limit = 'all')
{
    global $pgdb;

    if ($limit == 'all') {
        $query = "SELECT * FROM societe";
    } else {
        $query = "SELECT * FROM societe LIMIT $limit";
    }

    $societe = pg_query($pgdb, $query);
    if ($societe) {
        $temp = array();
        while ($so = pg_fetch_object($societe)) {
            $temp[] = $so;
        }

        return $temp;
    }

    return false;
}
function validateSiret($val)
{
    $is_error = 0;
    if (strlen(trim($val)) == 0 || $val == null || $val == '') {
        return "Siret Required!!!!";
    } elseif (!preg_match("/[0-9]{5}/", $val)) {
        return 'Siret must be 5 and digit only';

    }

    return false;
}

/**
 * @uses $pgdb
 */
function add_salarie    ()
{
    global $pgdb;

    $societe = intval($_POST['societe']);
    $nom = pg_escape_string($_POST['nom']);
    $prenom = pg_escape_string($_POST['prenom']);
    $tel = pg_escape_string($_POST['telephon']);
    $salaire = floatval($_POST['salaire']);

    $query = sprintf("INSERT INTO salaries(id_societe, nom, prenom, telephone, salaire)
                VALUES('%d', '%s', '%s', '%s', '%d')",
                $societe,
                $nom,
                $prenom,
                $tel,
                $salaire
            );
    echo $query;
    if (pg_query($pgdb, $query)) {
        echo 'Success for add new company';
    } else {
        echo 'Fail to add new societe';
    }
}
function edit_salarie()
{
}
function delete_salarie($id)
{
}
